﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Diagnostics;
using System.Data;
using Microsoft.MediaCenter;
using Microsoft.MediaCenter.Hosting;
using Microsoft.MediaCenter.UI;
using System.Xml;
using System.Text;
using MusicBrowser.LibraryManagement;


namespace MusicBrowser
{
    public class Setup : ModelItem
    {
      

        public Config Config
        {
            get { return Config.Instance; }
        }


        #region variables
        public string _setting = "1";        
        private ArrayListDataSet _checkedNodes = new ArrayListDataSet();
        private Choice _language = new Choice();
        public Choice _defaultView = new Choice();
        private BooleanChoice _transparent = new BooleanChoice();
        private BooleanChoice _useMusic = new BooleanChoice();
        private TreeView _treeView = null;        

        #endregion

        #region Properties

        public string Setting
        {
            get { return _setting; }
            set
            {
                _setting = value;
                FirePropertyChanged("Setting");
            }
        }

        public ArrayListDataSet CheckedNodes
        {
            get { return _checkedNodes; }
            set { _checkedNodes = value; }
        }

        public Choice Language
        {
            get { return _language; }
            set { _language = value; }
        }

        public Choice DefaultView
        {
            get { return _defaultView; }
            set { _defaultView = value; }
        }


        public BooleanChoice Transparent
        {
            get { return _transparent; }
            set { _transparent = value; }
        }
       
        public BooleanChoice UseMusic
        {
            get { return _useMusic; }
            set { _useMusic = value; }
        }

        #endregion


        public void IniSetup()
        {
            //Initialize Transparent Background
            Transparent.Value = Config.TransparentBackground;

            //Initialize Default View
           ArrayListDataSet tmp = new ArrayListDataSet();
            tmp.Add("List");
            tmp.Add("Thumb");
            tmp.Add("Poster");
            DefaultView.Options = tmp;

            try
            {
                DefaultView.Chosen = Config.DefaultView;
            }
            catch { }   

         
            //Initialize language
            ArrayListDataSet lang = new ArrayListDataSet();
            lang.Add("English");
            lang.Add("French");
            lang.Add("German");
            lang.Add("Dutch");
            Language.Options = lang;
            for (int i = 0; i <= lang.Count -1 ; i++)
            {
                if (lang[i].ToString().Substring(0, 2).ToLower() == Config.Lang) Language.Chosen = lang[i];
            }
            
            
           //Initialize folders
            if (Config.initialFolders.Contains("MyMusic")) UseMusic.Value = true;

            try { CheckedNodes.Clear(); }
            catch { }
            CheckedNodes = Config.initialFolders;
            try { CheckedNodes.Remove("mymusics"); }
            catch { }
            
        }
     

        public TreeView TreeView
        {
            get
            {
                if (_treeView == null)
                {
                    _treeView = new TreeView();
                  
                    foreach (DriveInfo dInfo in DriveInfo.GetDrives())
                    {
                        if (dInfo.DriveType == DriveType.Fixed || dInfo.DriveType == DriveType.Network)
                        {
                            if (dInfo.IsReady)
                            {
                                string dirName = dInfo.Name;
                                if (!string.IsNullOrEmpty(dInfo.VolumeLabel)) dirName += " (" + dInfo.VolumeLabel + ")";
                                DirectoryTreeNode node = new DirectoryTreeNode(dirName,
                                                                               dInfo.RootDirectory.FullName,
                                                                               _treeView);
                                if (Config.initialFolders.Contains(node.FullPath)) node.Checked.Value = true;
                                _treeView.ChildNodes.Add(node);
                                
                            }
                        }
                    }
                }

                return _treeView;
            }
            set { _treeView = value; }
        }


        

        private System.Text.StringBuilder sb;
       
        public void Save(Application app)
        {
                       
            DialogResult dr;
            MediaCenterEnvironment mce;
            mce = Microsoft.MediaCenter.Hosting.AddInHost.Current.MediaCenterEnvironment;

            object[] buttons = new object[2];
            buttons[0] = 4;
            buttons[1] = 8;

            dr = mce.Dialog(translate.Instance.SaveSettings(), "", buttons, 10, true, null, new DialogClosedCallback(OnButtnClick));

            if (dr == DialogResult.Yes)
            {
                //Save View setting
                if (DefaultView.Chosen.ToString() != Config.DefaultView) 
                    RewriteView();

                //Save Background setting
                Config.TransparentBackground = Transparent.Value;

                //Save Language setting
                Config.Lang = Language.Chosen.ToString().Substring(0,2).ToLower();

                //Save folder settings
                      
                string vf = Path.Combine(Helper.AppConfigPath,"VirtualFolder.vf");

                if (CheckedNodes.Count == 0)
                {
                    mce.Dialog(translate.Instance.SelectFolder(),"",DialogButtons.Ok,10,true);
                    return;
                }
                else if (CheckedNodes.Count == 1)
                {
                    Config.InitialFolder = CheckedNodes[0].ToString();
                    try { File.Delete(vf); }
                    catch { }
                }
                else
                {
                    sb = new System.Text.StringBuilder("");

                    for (int i = 0; i <= CheckedNodes.Count - 1; i++)
                    {
                        sb.AppendLine("folder: " + CheckedNodes[i].ToString());
                    }
                    
                    System.IO.File.WriteAllText(vf, sb.ToString());
                    Config.InitialFolder = vf;

                }
                if (!Directory.Exists(Helper.AppConfigPath)) Directory.CreateDirectory(Helper.AppConfigPath);
                if (!File.Exists(Config.filename)) File.WriteAllText(Config.filename, "<Settings></Settings>");
                Config.Write();

             /*   Dictionary<string, object> properties = new Dictionary<string, object>();
                properties["Application"] = app;
                properties["FolderItems"] = items;
                properties["Model"] = new ListPage(items);
                MyHistoryOrientedPageSession.Current.GoToPage("resx://MusicBrowser/MusicBrowser.Resources/Page", properties);
              * */
                Microsoft.MediaCenter.Hosting.AddInHost.Current.ApplicationContext.CloseApplication();
            }
            
            }

        public void OnButtnClick(Microsoft.MediaCenter.DialogResult buttn)
        {
        }

        private void RewriteView()
        {
            Config.DefaultView = DefaultView.Chosen.ToString();
            int defaultview = 0;


                if (DefaultView.Chosen.ToString() == "Thumb") defaultview = 1;
                else if (DefaultView.Chosen.ToString() == "Poster") defaultview = 2;

            try
            {
                foreach (string f in Directory.GetFiles(Helper.AppCachePath, "*.prefs.xml", SearchOption.TopDirectoryOnly))
                {
                    XmlDocument doc = new XmlDocument();
                    doc.Load(f);
                    int sort = Int32.Parse(doc.SelectSingleNode("Prefs/SortOrder").InnerText);

                    MemoryStream ms = new MemoryStream();
                    XmlWriter writer = new XmlTextWriter(ms, Encoding.UTF8);
                    writer.WriteStartDocument();
                    writer.WriteStartElement("Prefs");
                    writer.WriteElementString("SortOrder", sort.ToString());
                    writer.WriteElementString("ViewIndex", defaultview.ToString());
                    writer.WriteEndElement();
                    writer.Close();
                    ms.Flush();
                    File.WriteAllBytes(f, ms.ToArray());
                }
            }
            catch { }
        }

 

        public void AddNode(string node)
        {
          CheckedNodes.Add(node);
        }

        public void RemoveNode(string node)
        {
           
           CheckedNodes.Remove(node);
        }

        public void Cancel(AddInHost host)
        {
            //MyHistoryOrientedPageSession.Current.BackPage();
                       
        }

        public void Reset()
        {
            DialogResult dr;
            MediaCenterEnvironment mce;
            mce = Microsoft.MediaCenter.Hosting.AddInHost.Current.MediaCenterEnvironment;

            object[] buttons = new object[2];
            buttons[0] = 4;
            buttons[1] = 8;

            dr = mce.Dialog(translate.Instance.Reset()+"?", "", buttons, 10, true, null, new DialogClosedCallback(OnButtnClick));

            if (dr == DialogResult.Yes)
            {
                Directory.Delete(Helper.AppConfigPath, true);
                Microsoft.MediaCenter.Hosting.AddInHost.Current.ApplicationContext.CloseApplication();
            }
        }
        
    }
}
